package com.thoughtworks.android.androsphere.service.registration;

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.android.androsphere.dao.ClientRegistrationDao;
import com.thoughtworks.android.androsphere.dao.model.ClientRegistration;
import com.thoughtworks.android.androsphere.model.RegistrationRequest;

public class RegistrationServiceImpl implements RegistrationService {
    private ClientRegistrationDao clientRegistrationDao;

    public RegistrationServiceImpl(ClientRegistrationDao clientRegistrationDao) {
        this.clientRegistrationDao = clientRegistrationDao;
    }

    public void register(RegistrationRequest registrationRequest) {
        ClientRegistration clientRegistration = clientRegistrationDao.get(registrationRequest.getDevice());
        ClientRegistration newClientRegistration = new ClientRegistration(registrationRequest.getDevice(),
            registrationRequest.getRegistration());

        if(clientRegistration == null) {
            clientRegistrationDao.insert(newClientRegistration);
        } else if(!clientRegistration.getRegistrationId().equals(registrationRequest.getRegistration())) {
            clientRegistrationDao.update(newClientRegistration);
        }
    }

    public void unRegister(String deviceId) {
        clientRegistrationDao.delete(deviceId);
    }

    public List<String> peerRegistrationsFor(String broadcastingDeviceId) {
        List<String> peerRegistrations = new ArrayList<String>();

        final List<ClientRegistration> clientRegistrations = clientRegistrationDao.getAll();
        for(ClientRegistration clientRegistration : clientRegistrations) {
            if(!broadcastingDeviceId.equals(clientRegistration.getDeviceId())) {
                peerRegistrations.add(clientRegistration.getRegistrationId());
            }
        }
        return peerRegistrations;
    }
}
